package org.joy.pagerank;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.ObjectWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class PageRankDriver extends Configured implements Tool {

	public static void main(String[] args) throws Exception {
		int res = 0;
		for (int i = 0; i < 25; i++) {
			System.out.println("Round"+i);
			res = ToolRunner.run(new Configuration(), new PageRankDriver(),
					args);
		}
		System.exit(res);
	}

	@Override
	public int run(String[] arg0) throws Exception {
		// config a job and start it
		Configuration conf = getConf();
		Job job = new Job(conf, "Rank");
		job.setJarByClass(PageRankDriver.class);
		job.setMapperClass(PageRankMapper.class);
		job.setReducerClass(PageRankReducer.class);
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(ObjectWritable.class);
		job.setInputFormatClass(KeyValueTextInputFormat.class);
		FileInputFormat.addInputPath(job, new Path("in"));
		FileSystem fs = FileSystem.get(conf);
		fs.delete(new Path("out"), true);
		FileOutputFormat.setOutputPath(job, new Path("out"));
		int res = job.waitForCompletion(true) ? 0 : 1;
		if (res == 0) {
			fs.delete(new Path("in"), true);
			fs.rename(new Path("out"), new Path("in"));
		}
		return res;
	}

}
